package cn.hpclub.server.service;

import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.model.Broadband;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.ResultCode;

public class BroadbandService{
    private static final Logger    logger        = LoggerFactory.getLogger(BroadbandService.class);
    public static BroadbandService service       = new BroadbandService();

    public static final String[]   headesExport  = { "业务名称", "宽带类型", "业务简介", "宽带价格", "宽带带宽", "宽带品牌", "所属城市", "计费周期",
            "适用范围", "发布人", "发布人机构名称", "资费代码", "排序", "是否启用" };
    public static final String[]   columnsExport = { "name", "broadType", "business_summary", "price", "width", "brand",
            "city", "period", "businessType", "user_name", "org_name", "business_code", "order_num", "Enabled" };

    /**
     * 获取查询语句
     */
    public String getSqlExceptSelect(ConcurrentHashMap<String, String> searchInfo){
        String sqlExceptSelect = "from broadband b left join sys_user u on u.id = b.creator left join organization j on j.id = b.org_id where b.is_deleted = 0";
        int orgId = InterfaceUtil.getOrgId();
        String orgSql = InterfaceUtil.getChlidOrgIdSql(orgId, Constant.MAX_ORG_LEVEL, true);
        if(StrKit.notBlank(orgSql)){
            sqlExceptSelect += " and b.org_id in " + orgSql;
        }
        for(Entry<String, String> item : searchInfo.entrySet()){
            sqlExceptSelect += buildQuery(item);
        }
        sqlExceptSelect += " order by b.create_time desc,b.order_num asc";

        // System.out.println("sqlExceptSelect = " + sqlExceptSelect);
        return sqlExceptSelect;
    }

    /**
     * 获取查询语句
     */
    public List<Record> export(ConcurrentHashMap<String, String> searchInfo){
        String select = "select u.user_name,j.DisplayName org_name,b.*,(CASE b.enabled  WHEN  1 THEN '启用' WHEN 0 THEN '禁用' ELSE '未知' END ) as Enabled,(CASE broad_type WHEN  0 THEN '爱家小区' WHEN  1 THEN '优家小区' WHEN  2 THEN '商务动力' WHEN  3 THEN '校园套餐' ELSE '未知' END) as broadType, (CASE business_type WHEN  1 THEN '开户' WHEN  2 THEN '预约' WHEN  3 THEN '开户、预约' ELSE '未知' END) as businessType ";
        String sqlExceptSelect = "from broadband b left join sys_user u on u.id = b.creator left join organization j on j.id = b.org_id where b.is_deleted = 0";
        int orgId = InterfaceUtil.getOrgId();
        String orgSql = InterfaceUtil.getChlidOrgIdSql(orgId, Constant.MAX_ORG_LEVEL, true);
        if(StrKit.notBlank(orgSql)){
            sqlExceptSelect += " and b.org_id in " + orgSql;
        }
        for(Entry<String, String> item : searchInfo.entrySet()){
            sqlExceptSelect += buildQuery(item);
        }
        sqlExceptSelect += " order by b.create_time desc,b.order_num asc";

        List<Record> list = Db.find(select + sqlExceptSelect);
        return list;
    }

    private String buildQuery(Entry<String, String> item){
        String sql = "";
        if(item.getKey().equals("period")){
            sql += " and b.period = '" + item.getValue() + "'";
        } else if(item.getKey().equals("price")){
            sql += " and b.price = " + item.getValue() + "";
        } else if(item.getKey().equals("creator_name")){
            sql += " and b.creator in (select id from sys_user where user_name like '%" + item.getValue() + "%')";
        } else if(item.getKey().equals("creator_org")){
            sql += " and b.org_id in (select id from organization  where DisplayName like '%" + item.getValue() + "%')";
        } else if(item.getKey().equals("broad_type")){
            sql += " and b.broad_type=" + item.getValue() + "";
        } else{
            sql += " and b." + item.getKey() + " like '%" + item.getValue() + "%'";
        }
        return sql;
    }

    private String getOrgIds(){
        List<String> lst = InterfaceUtil.getOrganization();
        String t = lst.toString();
        t = t.replace('[', ' ').replace(']', ' ');
        return t;
    }

    public ResultCode delete(String[] ids){
        StringBuffer sb = new StringBuffer();
        sb.append("update broadband set is_deleted = 1" + " where id in(");
        if(ids.length > 0){
            for(int i = 0; i < ids.length; i++){
                logger.debug("id:" + ids[i]);
                if(i == ids.length - 1){
                    sb.append("?");
                } else{
                    sb.append("?,");
                }
            }
            sb.append(")");
        } else{
            return ResultCode.PARAM_ERROR;
        }

        logger.debug("BroadbandService delete sb=" + sb);

        boolean result = new Broadband().update(sb.toString(), ids);
        if(result){
            return ResultCode.SUCCESS;
        } else{
            return ResultCode.FAILED;
        }

    }

    /**
     * @Title: getGovBroadbandList
     * @Description:TODO
     * @param pageNumber
     * @param pageSize
     * @param orgId
     * @return Page<Record>
     */
    public Page<Record> getGovBroadbandList(int pageNumber, int pageSize, int orgId){
        return Broadband.dao.getGovBroadbandList(pageNumber, pageSize, orgId);
    }

    /**
     * @Title: getDetailByType
     * @Description:TODO
     * @param id
     * @param bd_type
     * @return Broadband
     */
    public Broadband getDetailByType(String id, String bd_type){

        return Broadband.dao.getDetailByType(id, bd_type);
    }

    /**
     * @Title: getListByType
     * @Description:TODO
     * @param pageNumber
     * @param pageSize
     * @param orgId
     * @param bd_type
     * @return Page<Record>
     */
    public Page<Record> getListByType(int pageNumber, int pageSize, int orgId, String bd_type){

        return Broadband.dao.getListByType(pageNumber, pageSize, orgId, bd_type);
    }

    /**
     * 根据多个id找到对应的code
     * 
     * @return
     */
    public String[] findCodesByIds(String[] ids){
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < ids.length; i++){
            if(i == ids.length - 1){
                sb.append(ids[i]);
            } else{
                sb.append(ids[i] + ",");
            }
        }

        List<Record> records = Db.find("select business_code from broadband where id in(" + sb.toString() + ")");
        String[] codes = new String[records.size()];
        int i = 0;
        for(Record record : records){
            codes[i++] = record.getStr(Broadband.BUSINESS_CODE);
        }
        return codes;
    }

    /**
     * @Title: getBroadbandByActType
     * @Description:TODO
     * @return JSONArray
     */
    public JSONArray getBroadbandByActType(){
        JSONArray busDatas = new JSONArray();
        List<Record> bdDataList = Broadband.dao.getBroadbandByActType();
        if(null != bdDataList && bdDataList.size() > 0){
            busDatas = JSONArray.parseArray(JsonKit.toJson(bdDataList));
        }
        return busDatas;
    }

}
